package bsf.baseservice.distributedcache.storage.aliyunmemcached;


import bsf.base.CallBack;
import bsf.baseservice.distributedcache.storage.BaseCache;
import bsf.base.TimeSpan;
import bsf.baseservice.distributedcache.systemruntime.DistributedCacheConnectException;
import bsf.baseservice.distributedcache.systemruntime.DistributedCacheSerializationException;
import bsf.serialization.json.JsonProvider;
import bsf.util.StringUtil;
import com.google.gson.JsonParseException;
import net.spy.memcached.MemcachedClient;
import net.spy.memcached.internal.OperationFuture;

public class AliyunMemcachedCache extends BaseCache
{
	private MemcachedClient client = null;
	@Override
	public <T> T getValue(final Class<T> cls)
	{
		//约定""为null的情况。 - null 表示未添加,""表示为null 这个未来要区分，目前暂时不区分
		return (T)tryCatch(new CallBack.Func0() {
			@Override
			public Object invoke(){
				String json = (String)client.get(cacheKey);
				if (json == null)
				{
					return null;
				}
				if (json.equals(""))
				{
					return null;
				}
				try
				{
					return  new JsonProvider().deserialize(json,cls);
				}
				catch (Exception exp)
				{
					throw new DistributedCacheSerializationException(StringUtil.nullToEmpty(json), exp);
				}
			}
		});
	}

	@Override
	public <T> boolean setValue(final T value,final TimeSpan expiretime)
	{
		//约定""为null的情况。
		 return (boolean) tryCatch( new CallBack.Func0() {
			@Override
			public  Object invoke(){
				String json = null;
				try
				{
					json = (value == null ? "" : new JsonProvider().serialize(value));
				}
				catch (Exception exp)
				{
					throw new DistributedCacheSerializationException(value.getClass(), exp);
				}
				OperationFuture r  = client.set(cacheKey, (int)expiretime.getSeconds(),json);
				boolean result = r.getStatus().isSuccess();
				if (!result)
				{
					throw new DistributedCacheConnectException("执行SetValue(Store)函数失败");
				}
				return result;
			}
		});
	}

	@Override
	public void delete()
	{
		tryCatch(new CallBack.Func0() {
				  @Override
				  public Object invoke() {
					  client.delete(cacheKey);
					  return null;
				  }
			  }
		);
	}

	@Override
	public void openConn(final String key)
	{
		tryCatch(new CallBack.Func0() {
				  @Override
				  public Object invoke(){
					  cacheKey = key;
					  AliyunMemcachedCacheConfig serverconfig = (AliyunMemcachedCacheConfig)Config;
					  client = new AliyunMemcachedClientPoolProvider().getPool(serverconfig);
					  return null;
				  }
			  }
		);
	}

	private  Object tryCatch(CallBack.Func0 action)
	{
		try
		{
			return action.invoke();
		}
		catch (JsonParseException e2)
		{
			throw new DistributedCacheSerializationException(e2);
		}
		/*
		catch (Enyim.Caching.Memcached.MemcachedClientException e3)
		{
			throw new DistributedCacheConnectException(e3.getMessage(), e3);
		}*/
	}

	@Override
	public void close()
	{
		if (client != null)
		{

		}
	}
}